package de.karlNet.Enums;

import java.util.HashSet;
import java.util.Set;

public class BinaryMaskEnumMapper<E extends Enum<?>> {
	private Class<? extends Enum<?>> enumToBeMapped;
	
	public BinaryMaskEnumMapper(Class<? extends Enum<?>> enumToBeMapped) {
		this.enumToBeMapped = enumToBeMapped;
	}
	
	public Set<E> getEnums(final int bitmask) {
		@SuppressWarnings("unchecked")
		E[] values = (E[]) this.enumToBeMapped.getEnumConstants();
		long mask = 1;
		mask = mask << (values.length -1);
		
		
		HashSet<E> enumValues = new HashSet<E>();
		for(int i=values.length;i>=0;i--) {
			long result = bitmask & mask;
			if(result > 0) {
				enumValues.add(values[i]);
			}
			mask = mask >> 1;
		}
		if(enumValues.size() <= 0) {
			enumValues.add((E) values[0]);
		}
		return enumValues;
	}
	
	public int fromList(Set<E> listOfEnumValues) {
		int ret = 0;
		for (E e : listOfEnumValues) {
			int ordinal = e.ordinal() - 1;
			ret |= 1 << ordinal;
		}
		return ret;
	}
}
